﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using System.Configuration;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckFullRecoveryModelWithNoLogBackup : IssueTypeCheckBase
    {
        public DatabaseCheckFullRecoveryModelWithNoLogBackup()
        {
            IssueTypeId = 3001;
        }

        public override void Check()
        {
            try
            {
                List<Issue> issues = new List<Issue>();

                HealthCheckDataContext dc = new HealthCheckDataContext(ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);

                var qry = from d in dc.Databases
                          where
                            d.RecoveryModel.ToLower() == "full"
                                &&
                            !d.LatestLogBackup.HasValue
                            && (d.DatabaseName != "model") && (d.DatabaseName != "master") && (d.DatabaseName != "msdb") && d.SourceDatabaseId == null
                          select d;

                foreach (var database in qry)
                {
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    //Create new Issue
                    Issue issue = new Issue();

                    issue.IssueType = issueType;
                    issue.TargetId = database.DatabaseID;
                    issue.Description = issueType.Description.Replace("{Database}", database.DatabaseName);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
    }
}
